package com.zrwl.poscloud.commons.utils;

import com.zrwl.poscloud.commons.validator.annotion.FileName;

import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BeanConvertorUtil {
    /**
     * @param src 带属性的实体 转  target被赋值的实体
     * @return void
     * @author lixiao 90183971
     * @date 2021/5/21 9:02
     */
    public static Object convertor(Object src, Object target) throws Exception {

        Class<?> srcClz = src.getClass();
        Class<?> targetClz = target.getClass();
        Field[] fields = srcClz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            //获取属性值
            Object value = field.get(src);
            if (value != null) {
                //获取注解
                FileName annotation = field.getAnnotation(FileName.class);
                if (annotation != null && annotation.name() != null) {
                    //获取当前方法的参数类型
                    Class<?> c = getMethodParamTypes(target, "set" + captureName(annotation.name()));
                    //获取当前方法
                    Method method = targetClz.getMethod("set"+captureName(annotation.name()), c);
                    method.setAccessible(true);
                    method.invoke(target, (Object) value);
                }
            }

        }
        return target;
    }

    /**
     * @param src 不带属性的实体 转  target  带属性被赋值的实体
     * @return void
     * @author lixiao 90183971
     * @date 2021/5/21 9:02
     */
    public static Object reverseConvertor(Object src, Object target) throws Exception {

        Class<?> srcClz = src.getClass();
        Class<?> targetClz = target.getClass();

        Field[] fields = srcClz.getDeclaredFields();
        Method[] declaredMethods = srcClz.getDeclaredMethods();
        for (Method declaredMethod : declaredMethods) {
            if(declaredMethod.getName().contains("get")){
                //获取属性值
                Object value = declaredMethod.invoke(src);
                //获取属性名
                String attributeName = getAttributeName(targetClz, declaredMethod.getName().substring(3).substring(0,1).toLowerCase()+declaredMethod.getName().substring(3).substring(1));
                if(attributeName != null && value != null ){
                    //获取当前方法的参数类型
                    Class<?> c = getMethodParamTypes(target, "set" + captureName(attributeName));
                    //获取当前方法
                    Method method = targetClz.getMethod("set" + captureName(attributeName), c);
                    method.setAccessible(true);
                    method.invoke(target, (Object) value);
                }
            }
        }
        return target;
    }

    //方法首字母大写
    private static String captureName(String name) {
        name = name.substring(0, 1).toUpperCase() + name.substring(1);
        return name;
    }

    //获取方法的类型
    private static Class<?> getMethodParamTypes(Object classInstance, String methodName) {
        //全部方法
        Method[] methods = classInstance.getClass().getMethods();
        Class<?> param = null;
        for (int i = 0; i < methods.length; i++) {
            //和传入方法名匹配
            if (methodName.equals(methods[i].getName())) {
                param = methods[i].getParameterTypes()[0];
                break;
            }
        }
        return param;
    }

    private static String getAttributeName(Class<?> targetClz, String name) {
        Field[] declaredFields = targetClz.getDeclaredFields();
        String attributeName = null;
        for (Field field : declaredFields) {
            FileName annotation = field.getAnnotation(FileName.class);
            if(annotation != null && name.equals(annotation.name())){
                    attributeName = field.getName();
                    break;
            }

        }
        return attributeName;
    }
    /**
     * 比较两个实体属性值，返回一个boolean,true则表时两个对象中的属性值无差异
     * @param oldObject 进行属性比较的对象1
     * @param newObject 进行属性比较的对象2
     * @return 属性差异比较结果boolean
     */
    public static boolean compareObject(Object oldObject, Object newObject) {
        Map<String, Map<String,Object>> resultMap=compareFields(oldObject,newObject);

        if(resultMap.size()>0) {
            return false;
        }else {
            return true;
        }
    }
    /**
     * 比较两个实体属性值，返回一个map以有差异的属性名为key，value为一个Map分别存oldObject,newObject此属性名的值
     * @param oldObject 进行属性比较的对象1
     * @param newObject 进行属性比较的对象2
     * @return 属性差异比较结果map
     */
    @SuppressWarnings("rawtypes")
    public static Map<String, Map<String,Object>> compareFields(Object oldObject, Object newObject) {
        Map<String, Map<String, Object>> map = null;

        try{
            /**
             * 只有两个对象都是同一类型的才有可比性
             */
            if (oldObject.getClass() == newObject.getClass()) {
                map = new HashMap<String, Map<String,Object>>();

                Class clazz = oldObject.getClass();
                //获取object的所有属性
                PropertyDescriptor[] pds = Introspector.getBeanInfo(clazz,Object.class).getPropertyDescriptors();

                for (PropertyDescriptor pd : pds) {
                    //遍历获取属性名
                    String name = pd.getName();

                    //获取属性的get方法
                    Method readMethod = pd.getReadMethod();

                    // 在oldObject上调用get方法等同于获得oldObject的属性值
                    Object oldValue = readMethod.invoke(oldObject);
                    // 在newObject上调用get方法等同于获得newObject的属性值
                    Object newValue = readMethod.invoke(newObject);

                    if(oldValue instanceof List){
                        continue;
                    }

                    if(newValue instanceof List){
                        continue;
                    }

                    if(oldValue instanceof Date){
                        oldValue = (Date) oldValue;
                    }

                    if(newValue instanceof Date){
                        newValue = (Date) newValue;
                    }

                    if(oldValue == null && newValue == null){
                        continue;
                    }else if(oldValue == null && newValue != null){
                        Map<String,Object> valueMap = new HashMap<String,Object>();
                        valueMap.put("oldValue",oldValue);
                        valueMap.put("newValue",newValue);

                        map.put(name, valueMap);

                        continue;
                    }

                    if (!oldValue.equals(newValue)) {// 比较这两个值是否相等,不等就可以放入map了
                        Map<String,Object> valueMap = new HashMap<String,Object>();
                        valueMap.put("oldValue",oldValue);
                        valueMap.put("newValue",newValue);

                        map.put(name, valueMap);
                    }
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }

        return map;
    }
}
